package xin.nick.demo;

//写一段java多线程代码，完成如下逻辑，同时启动3个线程从1开始打印递增数字，
// 每次每个线程打印3次，打印到36程序结束，

/**
 * @author inick
 * @Auther: Nick inickning@outlook.com
 * @Date: 2021/3/18 20:59
 * @Description:
 */
public class MyThread1 extends Thread{
    public static int count = 1;

    public static final int MAX_COUNT = 36;
    public static final int RUN_COUNT = 3;

    private int cid = 1;
    private int nid = 2;

    public void setCid(int cid) {
        this.cid = cid;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (MyThread1.class) {
                if(MyThread1.count < MyThread1.MAX_COUNT) {
                    nid = MyThread1.count / 3 % 3 + 1;
//                    System.out.println(cid + "--" + nid);
                    if(cid == nid) {
                        for(int i = 0; i < RUN_COUNT; i++) {
                            System.out.println("线程" + cid + ": " + count++);
                        }
                        MyThread1.class.notifyAll();
                    } else {
                        try {
                            MyThread1.class.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    break;
                }
            }

        }
    }

    public static void main(String[] args) {
        MyThread1 myThread1 = new MyThread1();
        myThread1.setCid(1);

        MyThread1 myThread2 = new MyThread1();
        myThread2.setCid(2);

        MyThread1 myThread3 = new MyThread1();
        myThread3.setCid(3);

        myThread1.start();
        myThread2.start();
        myThread3.start();

    }
}
